import http from '@/common/js/api.js'

/* 数据字典 根据code翻译name*/
function selectdata(cls, clsson) {
  let dictionaryName = ''
  const cache = sessionStorage.getItem('dictionaryList') ? sessionStorage.getItem('dictionaryList') : null
  if (cache) {
    JSON.parse(cache).some(item => {
      if (item[cls] && Array.isArray(item[cls])) {
        item[cls].some(i => {
          if (i.code == clsson) {
            dictionaryName = i.name
            return true
          }
        })
      }
    })
    if (dictionaryName != '') {
      return dictionaryName
    }
  }
  return ''
}
// 同步查询数据字典list并缓存
function querydata(cls, bool = false) {
  var flag = false
  var list = []
  var cache = sessionStorage.getItem('dictionaryList')
  if (!bool) {
    if (cache) {
      JSON.parse(cache).some(item => {
        if (item[cls]) {
          flag = true
          list = item[cls]
          return true
        }
      })
    }
  }
  if (!flag) {
    return new Promise((resolve, reject) => {
      http.get('/ly-oms-servicer/dictionary/content/list/condition?status=true&type=' + cls, {}, res => {
        if (res.code == '0') {
          var cache = sessionStorage.getItem('dictionaryList')
          var list = cache == null ? [] : JSON.parse(cache)
          var json = {}
          json[cls] = res.responseBody
          list.push(json)
          sessionStorage.setItem('dictionaryList', JSON.stringify(list))
          resolve(res.responseBody)
        }
      })
    })
  } else {
    return list
  }
}

/**
 * 使用方式
 *   async 方法名 () {
      let list = await this.querydata('FPLX')  querydata（）返回是当前查询的数据list
      let list2 = await this.querydata('SPFL')

       let res = this.selectdata('FPLX', 'PTFP')  selectdata（）查询后code再进行翻译返回name
    let ress = this.selectdata('SPFL', 'yiwuqingjie')
    }
 */
export { selectdata, querydata }
export default { selectdata, querydata }
